// pages/goods/payfor.js
var app = getApp();
var a = app.requirejs("core");
Page({
  data:{
    addressData:{},
    address:{},
    show:false,
    disabled: false,
    freight:0,
    totalPrice:0,
    data: [],
    list: {},
    is_mention: 1,//1邮寄，2自提，3自选
    send_type: 'express',
    date: '',
    time: '17:00',
    mailing_type: 1,
    mention_time: 0
  },

  // 自提、邮寄
  dispatchtype: function(e) {
    var data = a.pdata(e);
    this.setData(data);
  },

  // 日期选择
  bindDateChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    var get_time = a.time_str(e.detail.value + ' ' + this.data.time);
    var now_time = Date.parse(new Date()) / 1000;

    if (now_time > get_time) {
      a.error('不小于当前时间');
      return;
    }
    this.setData({
      date: e.detail.value
    })
  },

  // 时间选择
  bindTimeChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      time: e.detail.value
    })
  },

  onLoad: function (options) {
    var self = this;
    wx.showLoading({
        title : "正在加载",
        mask  : true,
    });

    a.get("user/About", {
      user_id: getApp().getCache("userinfo").uid
    }, function (t) {
      if (t.code == 0) {
        var send_type = self.data.send_type;
        if (t.info.is_mention == 2 || t.info.is_mention == 6) {
          send_type = 'selftake';
        } else if (t.info.is_mention == 4) {
          send_type = 'endpay';
        }

        self.setData({
          user_level: t.info.user_level,
          user_rebate: t.info.user_rebate,
          is_mention: t.info.is_mention,
          send_type: send_type
        })
      }
    })
    console.log("addr",app.goodsInfo);
    self.setData({
      address: app.goodsInfo.address,
      goodsNum: app.goodsInfo.num,
      goodsInfo: app.goodsInfo,
      goodsPrice: app.goodsInfo.goodsPrice,
      totalPrice: (app.goodsInfo.goodsPrice * app.goodsInfo.num).toFixed(2),
      show:true
    })
    wx.hideLoading();
  },

  onShow:function(options){
    var i = this,
        d = app.getCache("orderAddress");
    console.log("addr1",d);
    if (d) {
      d.userName = d.consigner;
      d.telNumber = d.phone;
      i.setData({
        address: d
      })
    }
  },

  showAddressList:function(){
    wx.navigateTo({
      url: '/yb_mingpian/pages/member/address/select'
    })
  },

  // 信息输入
  dataChange: function (t) {
    var e = this.data.address;

    switch (t.target.id) {
      case "buyer_message":  //留言
        e.buyer_message = t.detail.value;
        break;
      case "consigner":
        e.userName = t.detail.value;
        break;
      case "phone":
        e.telNumber = t.detail.value;
        break;
    }
    this.setData({
      data: e,
    })
  },

  // 立即支付
  formSubmit:function(v){
    var self = this,
        t = self.data;

    if (t.send_type == 'selftake') {
      if (!t.address.userName) {
        app.showToast(self,'请填写姓名');
        return false;
      }
      if (!t.address.telNumber) {
        app.showToast(self,'请填写电话');
        return false;
      }
      if (!t.date) {
        app.showToast(self,'请选择自提日期');
        return false;
      }
      t.mention_time = a.time_str(t.date + ' ' + t.time);
      t.mailing_type = 2;
    } else if (t.send_type == 'endpay') {
      if (!t.address.telNumber || t.address.userName == '') {
        app.showToast(self,'请选择收货地址');
        return false;
      }
      t.mailing_type = 4;
    } else {
      if (!t.address.userName || t.address.telNumber == '') {
        app.showToast(self,'请选择收货地址');
        return false;
      }
      t.mailing_type = 1;
    }

    var data = {
      pid: self.data.goodsInfo.groupPid,
      isGroup: self.data.goodsInfo.buyType,
      gid: self.data.goodsInfo.id,
      goodsNum: self.data.goodsNum,
      limitTime: self.data.goodsInfo.limitTime,
      address: JSON.stringify(self.data.address),
      totalPrice: (self.data.goodsInfo.goodsPrice * self.data.goodsNum) + parseFloat(self.data.freight),
      uid:app.getCache('userinfo').uid,
      mailing_type: t.mailing_type,
      mention_time: t.mention_time,
    }
    if(t.oid || t.disabled){
      return false;
    }

    self.setData({
      disabled: true
    }),

    wx.showLoading({
      title: '正在提交',
      mask : true,
    })
    var formId = v.detail.formId;
    a.get('Pintuan/ptCreateOrder',data,function(i){
      wx.hideLoading();
      if(i.code==0) {
        //推送
        a.get('Wxpush/CreateOrderPush3', {
          order_id: i.info,
          formid: formId,
          uid: getApp().getCache("userinfo").uid,
        }, function (tt) {

          // console.log(tt)
          // console.log(22222222);
        })
        self.setData({
          oid: i.info,
          disabled: false
        })

        // 订单金额为0时调用接口，支付成功
        if (data.totalPrice == 0) {
          a.get("pay/updPayStatus", {
            order_id: i.info,
            pay_type: 2
          }, function(res) {
            if (res.code == 1) {
              if (data.isGroup == 1) {
                // 重定向到团详情页面
                wx.redirectTo({
                  url: '/yb_mingpian/pages/pintuan/pages/group/detail?id=' + i.info,
                })
              } else {
                // 重定向到订单页面
                wx.redirectTo({
                  url: '/yb_mingpian/pages/pintuan/pages/orders/index',
                })
              }
            } else {
              a.alert(res.msg)
            }
          })
        } else {
          a.get('Pintuan/ptPay', {
            oid: i.info,
            openid: getApp().getCache("userinfo").openid
          }, function (t) {
            if (t.code == 0) {
              wx.requestPayment({
                'timeStamp': t.info.timeStamp,
                'nonceStr': t.info.nonceStr,
                'package': t.info.package,
                'signType': 'MD5',
                'paySign': t.info.paySign,
                'success': function (res) {
                  console.log(res)
                  if (data.isGroup == 1) { //拼团
                    // 重定向到团详情页面
                    wx.redirectTo({
                      url: '/yb_mingpian/pages/pintuan/pages/group/detail?id=' + i.info,
                    })
                    // app.redirect('group/detail','id='+oid)
                  } else {
                    // 重定向到订单页面
                    wx.redirectTo({
                      url: '/yb_mingpian/pages/pintuan/pages/orders/index',
                    })
                    // app.redirect('orders/index','id=3')
                  }
                  console.log(i.info)
                  console.log(7777777777)
                  a.get('Wxpush/PtSuccessPush', {
                    pid: i.info,
                  }, function (ab) {
                    console.log(ab)
                    console.log('------------')
                  })

                },
                'fail': function (res) {
                  a.alert('您已取消了支付', function () {
                    wx.redirectTo({
                      url: '/yb_mingpian/pages/pintuan/pages/orders/index',
                    })
                  })
                }
              })
            } else {
              a.alert(t.msg, function () {
                wx.redirectTo({
                  url: '/yb_mingpian/pages/pintuan/pages/orders/index',
                })
              });
            }
          })
        }
      }else{
        self.setData({
          disabled: false
        })
        a.alert(i.msg)
      }
    })
 
  },

  minus:function(){
    var num = this.data.goodsNum > 1 ? --this.data.goodsNum : 1
    var totalPrice = (this.data.goodsPrice*num);
    this.setData({
      goodsNum : num,
      totalPrice:totalPrice.toFixed(2)
    })
  },
  plus:function(){
    if (this.data.goodsInfo.buyType == 1 || this.data.goodsPrice == 0) {
      a.alert('限购数量为1')
      return false
    }

    var num = this.data.goodsNum < this.data.goodsInfo.stock ? ++this.data.goodsNum : this.data.goodsInfo.stock;
    var totalPrice = (this.data.goodsPrice*num);
    this.setData({
      goodsNum : num,
      totalPrice:totalPrice.toFixed(2)
    })
  }
})